#include "xsnExtractor.h"

namespace xsn
{
	std::string Extractor::extract( ConstNodePtr node )
	{
		static Extractor instance;
		std::string result;
		instance.format(node,result,0);
		return result;
	}

	bool Extractor::isMultiNode( ConstNodePtr node ) const
	{
		bool result = (node->childCount() > 1);		
		for(size_t i=0 ; i < node->childCount() ; i++)
		{
			ConstNodePtr child = node->getChild(i);			
			while(child)
			{
				result |= this->isMultiNode(child);
				child = child->getAttrib(1);
			}			
		}
		return result;
	}

	void Extractor::format( ConstNodePtr node,std::string& src,size_t indent )
	{
		src += node->get();
		if(node->childCount() > 0)
		{
			bool thisIsMultiNode = this->isMultiNode(node);
			if(thisIsMultiNode)
			{
				src += "\n"+std::string(indent,'\t');
			}
			src += "[";	

			for(size_t i=0 ; i < node->childCount() ; i++)
			{
				if(thisIsMultiNode)
				{
					src += "\n"+std::string(indent+1,'\t');
				}	
				else
				{
					src += " ";
				}
				ConstNodePtr nextChild = node->getChild(i);
				while(nextChild)
				{										
					this->format(nextChild,src,indent+1);
					nextChild = nextChild->getAttrib(1);
					src += " ";
					if(!nextChild && node->childCount() > 1)
					{
						src[src.length()-1] = ';';
					}
				}
			}

			if(thisIsMultiNode)
			{
				src += "\n"+std::string(indent,'\t');
			}
			src += "]";	
		}
	}
}
